package utils.db.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pojo.Device;
import pojo.EDeviceState;
import pojo.EDeviceType;
import pojo.EUserType;
import pojo.User;
import utils.db.helper.impl.QueryDetailer;

public class Mapper implements IMapper {
	private static Logger logger = LoggerFactory.getLogger(Mapper.class);
	private QueryDetailer detailer;

	@Override
	public Device deviceMapp(ResultSet rs) {
		Device device = new Device();
		try {
			device.setId(rs.getInt("id"));
			device.setDescription(rs.getString("description"));
			device.setType(EDeviceType.valueOf(rs.getString("type")
					.toUpperCase()));
			device.setState(EDeviceState.valueOf(rs.getString("state")
					.toUpperCase()));
			device.setDate(rs.getDate("date"));
			device.setClientId(rs.getInt("client_id"));
			device.setServicemanId(rs.getInt("serviceman_id"));
		} catch (SQLException e) {
			logger.error("Error during execute query");
			e.printStackTrace();
		}
		logger.info("Retrieve device " + device.toString());
		return device;
	}

	@Override
	public User userMapp(ResultSet rs) {
		User user = new User();
		try {
			user.setId(rs.getInt("id"));
			user.setEmail(rs.getString("email"));
			user.setFirstName(rs.getString("firstName"));
			user.setLastName(rs.getString("lastName"));
			user.setPassword(rs.getString("password"));
			user.setPhoneNumber(rs.getInt("phoneNumber"));
			user.setType(EUserType.parse(rs.getString("type")));
		} catch (SQLException e) {
			logger.error("Error during execute query");
			System.err.println(e);
		}
		logger.info("Retrieve user " + user.toString());
		return user;
	}

	@Override
	public List<User> usersMapp(ResultSet rs) {
		List<User> users = new ArrayList<User>();
		try {
			detailer = new QueryDetailer(rs);
			rs.beforeFirst();
			for (int i = 0; i < detailer.getRow(); i++) {
				while (rs.next()) {
					users.add(this.userMapp(rs));
				}
			}
		} catch (SQLException e) {
			logger.error("Error during map data from ResultSet to Users List");
			return null;
		}
		return users;
	}

	@Override
	public List<Device> devicesMapp(ResultSet rs) {
		List<Device> devices = new ArrayList<Device>();
		try {
			detailer = new QueryDetailer(rs);
			rs.beforeFirst();
			for (int i = 0; i < detailer.getRow(); i++) {
				while (rs.next()) {
					devices.add(this.deviceMapp(rs));
				}
			}
		} catch (SQLException e) {
			logger.error("Error during map data from ResultSet to Users List");
			return null;
		}
		return devices;
	}
}
